package ranab.gui;

import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.StringReader;
import java.io.Writer;

import javax.swing.JTextArea;


/*
 * This class encapsulates <code>java.io</code>.
 * 
 * @author <a href="mailto:rana_b@yahoo.com">Rana Bhattacharyya</a>
 */
public
class TextAreaIo {
    
    /**
     * Maximum number of characters in the text area to be written.
     * Currently it is 4k.
     */
    public final static int MAX_SIZE = 4096;
    
    /**
     * Get <code>java.io.StringReader</code> object to read text area data.
     */
    public static StringReader getReader(JTextArea area)  {
        return new StringReader(area.getText());
    }
    
    /**
     * Get <code>java.io.InputStream</code> object to read text area data.
     */
    public static DataInputStream getInputStream(JTextArea area)  {
        return new DataInputStream(new ByteArrayInputStream(area.getText().getBytes()));
    }
    
    /**
     * Get <code>java.io.PrintWriter<code> object to write in the text area.
     */
    public static PrintWriter getWriter(final JTextArea area)  {
        return new PrintWriter( new Writer()  {
                public void write(char[] cbuf, int off, int len) {
                    if(area.getText().length()>MAX_SIZE) {
                        area.setText("");
                    }
                    area.append(new String(cbuf, off, len));
                }    
                
                public void close()  {
                }
                
                public void flush()  {
                }
            }
        );
    }
    
    /**
     * Get <code>java.io.PrintStream</code> to write in the text area.
     */
    public static PrintStream getOutputStream(final JTextArea area)  {
        return new PrintStream( new OutputStream()  {
                public void write(int b)  {
                    if(area.getText().length()>MAX_SIZE) {
                        area.setText("");
                    }
                    String str = new String(new byte[]  {(byte)b}); 
                    area.append(str);                
                }
                
                public void write(byte[] b, int off, int len)  {
                    if(area.getText().length()>MAX_SIZE) {
                        area.setText("");
                    }
                    String str = new String(b, off, len);
                    area.append(str);
                }
            }
        );
    }
}
